package com.atguigu.gmall.auth.service;

import com.atguigu.gmall.auth.config.JwtProperties;
import com.atguigu.gmall.auth.feign.GmallUmsClient;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.AuthException;
import com.atguigu.gmall.common.utils.CookieUtils;
import com.atguigu.gmall.common.utils.IpUtils;
import com.atguigu.gmall.common.utils.JwtUtils;
import com.atguigu.gmall.ums.entity.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@EnableConfigurationProperties(JwtProperties.class)
@Service
public class AuthService {

    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private GmallUmsClient gmallUmsClient;

    public void login(String loginName, String password, HttpServletRequest request, HttpServletResponse response) throws AuthException {
        //1.远程调用ums的接口，效验登录名和密码是否正确
        ResponseVo<UserEntity> responseVo = this.gmallUmsClient.query(loginName,password);
        UserEntity userEntity = responseVo.getData();

        //2.判空 如果为空 说明登录名或者密码不正确
        if (userEntity == null){
            throw new AuthException("用户名或者密码错误!");
        }

        //3.组装载荷
        Map<String , Object> map = new HashMap<>();
        map.put("userId" , userEntity.getId());
        map.put("username" , userEntity.getUsername());

        //4.为了防止盗用，在载荷中加入登录用户的ip地址
        String ip = IpUtils.getIpAddressAtService(request);
        map.put("ip", ip);

        try {
            //5.制作jwt
            String token = JwtUtils.generateToken(map, this.jwtProperties.getPrivateKey(), this.jwtProperties.getExpire());

            //6.放入cookie中
            CookieUtils.setCookie(request, response, this.jwtProperties.getCookieName(), token, this.jwtProperties.getExpire() * 60);

            //7.放入昵称
            CookieUtils.setCookie(request, response, this.jwtProperties.getUnick(), userEntity.getUsername(), this.jwtProperties.getExpire() * 60);
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthException("服务器端错误，登录失败");
        }

    }
}
